// 提交链接 https://leetcode.cn/problems/longest-univalue-path/submissions/569644603/
// 687 最长同值路径
// 完成日期： 2024.10.7
// 树状dp
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    unordered_map<int, int> ma;
    int longestUnivaluePath(TreeNode* root) {
        int ans = 0;
        if (root) dfs(root);
        for (auto& x : ma) ans = max(ans, x.second);
        return ans;
    }
    int dfs(TreeNode* root)
    {
        int ans = 0, num = 0;
        if (root->left && root->left->val == root->val)
        {
            int temp = dfs(root->left);
            ans += temp + 1;
            num = max(num, temp + 1);
        }
        else if (root->left) dfs(root->left);
        if (root->right && root->right->val == root->val)
        {
            int temp = dfs(root->right);
            ans += temp + 1;
            num = max(num, temp + 1);
        }
        else if (root->right) dfs(root->right);
        ma[root->val] = max(ans, ma[root->val]);
        return num;
    }
};